Like any kind of apps, there are difficult issues to solve when we write Node apps.
In this article, we’ll look at some solutions to common problems when writing Node apps.
Share Constants in NodeJS Modules
We can share constants in Node modules by exporting a frozen object.
For instance, we can write:
constants.js
module.exports = Object.freeze({
FOO: 'foo',
BAR: '123'
});
We call the Object.freeze
method to freeze the object with the constants.
Then in another module, we can require by writing:
const constants = require('./constants');
Send Responses to All Clients Except Sender with Socket.io
There are multiple ways to send a response to all clients except the sender with Socket.io.
Yo send to the sender only, we can write:
socket.emit('message', "hello");
To send to all clients except the sender, we can write:
socket.broadcast.emit('message', "hello");
To send to all clients in a room except for the sender, we can write:
socket.broadcast.to('chatRoom').emit('message', 'hello');
To send to all clients including the sender, we write:
io.emit('message', "hello");
To send to all clients in a room including the sender, we can write:
io.in('chatRoom').emit('message', 'hello');
To send to the sender only in a room, we can write:
`socket.to('`chatRoom`').emit('message', 'hello');`
To send to all clients in a namespace, we can write:
io.of('namespace').emit('message', 'hello');
To send to a socket ID, we can write:
socket.broadcast.to(socketId).emit('message', 'hello');
Reasons to use Promise Libraries like Q or BlueBird
We can use promise libraries like Q or Bluebird to convert existing async functions to return promises.
For instance, we can write:
const Promise = require('bluebird');
const fs = Promise.promisifyAll(require('fs'));
fs.readFileAsync('foo.text').then((data) => {
//...
});
We used Bluebird to convert everything in the fs
module to promises.
So we can use methods like readFileAsync
to read files asynchronously.
There are also methods exclusive to Bluebird that aren’t available with the ES6 Promise
constructor.
Promise.promisify()
converts Node callbacks to promises.
Promise.map()
maps arrays to promises.
Promise.reduce()
lets us map values to promises and invoke them sequentially and reduce the resolved values to a single value.
Promise.mapSeries()
takes values, map them to promises, and run them in series.
Then we get the values of them at the end.
Promise.delay()
lets us dealt a promise by a given number of milliseconds.
Node.js Global Variables
We can add a property to global
to add a global variable.
For instance, we can write:
global._ = `require('underscore');`
Node.js Get File Extension
We can get the file extension of a file name with the extname
method.
For instance, we can write:
const path = require('path');
path.extname('index.html');
Run Function in Script from Command Line
We can run a function in a script from the command line with node -e
.
If we have a module, we can write:
hi.js
module.exports.hello = () => {
console.log('hello');
};
For instance, we can write:
node -e 'require("./hi").hello()'
Difference Between res.send and res.json in Express.js
res.send
and res.json
are the same when arrays or objects are passed in.
However, if non-objects are passed in, then res.json
also converts those values to something that can be returned.
res.json
calls res.send
in the end.
Passing Variables to the Next Middleware Using next() in Express.js
We add a property to the req
variable to pass data to the next middleware.
For instance, we can write:
req.foo = 'bar';
Then we can access req.foo
in the next middleware.
Also, we can add a property to the res.locals
property to do the same thing.
Use Node.js Crypto to Create an HMAC-SHA1 Hash
We can use the Node crypto module to create an HMAC-SHA1 hash.
For instance, we can write:
const crypto = require('crypto')
const text = 'hello world';
const key = 'secret';
crypto.createHmac('sha1', key)
.update(text)
.digest('hex')
We call the createHmac
method to create a hash from the key
.
And then we hash the text
with it with update
and convert it to hex with update
.
Conclusion
We can use the crypto
module to hash text.
There are many ways to send data with socket.io.
We can get the extension of a file name with the path
module.
Promise libraries are still useful.
global
is the global object in Node.